using Microsoft.AspNetCore.Mvc;
using RuoVea.ExDto;
using RuoVea.OmiApi.Reports.Dto;
using RuoVea.OmiApi.Reports.Service;
using RuoVea.OmiReports.Attributes;
using System.Data;
using System.Text;

namespace RuoVea.OmiReports.Controllers;

/// <summary>
/// 
/// </summary>
[AppRoute]
public class RptQueryController : Controller
{
    private readonly RptSqlService _ReportService;
    private readonly RptSqlColumnService _reportSqlColumnService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="reportService"></param>
    /// <param name="reportSqlColumnService"></param>
    public RptQueryController(RptSqlService reportService, RptSqlColumnService reportSqlColumnService)
    {
        _ReportService = reportService;
        _reportSqlColumnService = reportSqlColumnService;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet(nameof(Index))]
    public IActionResult Index(long id,string name)
    { 
        ViewBag.id = id;
        ViewBag.name = name;
        return View();
    }

    /// <summary>
    /// 查询报表
    /// </summary>
    /// <param name="parm"></param>
    /// <returns></returns>
    [HttpGet("list/{Id}")]
    public async Task<RestfulResult<PageResultDto>> ListAsync([FromRoute] long id, [FromForm][ModelBinder(BinderType = typeof(DictionaryBinder))] Dictionary<string, string> parm)
    {
        var response = await _ReportService.GetListAsync(id, parm);
        return response;
    }

    /// <summary>
    /// 数据导出
    /// </summary>
    [HttpGet("export/{id}")]
    public async Task<IActionResult> ExportAsync([FromRoute] long id, [FromQuery] string name, [FromForm][ModelBinder(BinderType = typeof(DictionaryBinder))] Dictionary<string, string> parm)
    {
        try
        {
            parm["pageNo"] = "1";
            parm["pageSize"] = ushort.MaxValue.ToString();

            var exportTable = await _ReportService.ExportAsync(id, parm);

            // 生成CSV内容（带BOM）
            var csvData = GenerateCsvContent(exportTable);
            var fileName = $"{name?? "报表数据"}_{DateTime.Now:yyyyMMddHHmmss}.csv";

            // 返回文件流，指定编码
            return File(csvData, "text/csv; charset=utf-8", fileName);
        }
        catch (Exception ex)
        {
            return BadRequest("导出失败：" + ex.Message);
        }
    }


    /// <summary>
    /// 生成CSV内容（带BOM头）
    /// </summary>
    private byte[] GenerateCsvContent(DataTable data)
    {
        using (var memoryStream = new MemoryStream())
        using (var writer = new StreamWriter(memoryStream, new UTF8Encoding(true))) // 添加BOM
        {
            // 写入列头
            var headers = data.Columns.Cast<DataColumn>().Select(col => EscapeCsvField(col.ColumnName));
            writer.WriteLine(string.Join(",", headers));

            // 写入数据行
            foreach (DataRow row in data.Rows)
            {
                var values = row.ItemArray.Select(field => EscapeCsvField(field));
                writer.WriteLine(string.Join(",", values));
            }

            writer.Flush();
            return memoryStream.ToArray();
        }
    }

    /// <summary>
    /// 转义CSV字段（处理逗号、引号、换行符等）
    /// </summary>
    private string EscapeCsvField(object field)
    {
        if (field == null || field == DBNull.Value)
            return string.Empty;

        string str = field.ToString();

        // 处理日期时间
        if (field is DateTime dateTime)
        {
            str = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
        }

        // 如果字段包含逗号、引号、换行符，需要用引号包围并转义内部引号
        if (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"))
        {
            str = "\"" + str.Replace("\"", "\"\"") + "\"";
        }

        return str;
    }
}